import { ref, reactive } from "vue";
import "jbecool/jbecool.uniapp.min.js";
import VMControl from "@/js/VMControl.js";

J.api.apiUrl = "http://127.0.0.1:8089/__api__";

class AdminRegisterControl extends VMControl {
  constructor() {
    super("OBEvolutionAI.AdminControl", "adminId");

    // 表单数据
    this.currentModel = reactive({
      username: "",
      password: "",
      confirmPassword: "",
      realname: "",
      num: "",
      email: "",
      phone: "",
      schoolId: "",
      title: "",
    });

    // 表单验证规则
    this.rules = {
      username: [
        {
          required: true,
          message: "用户名不能为空",
          trigger: ["blur", "change"],
        },
        { min: 2, max: 20, message: "用户名长度2-20位", trigger: "blur" },
      ],
      password: [
        {
          required: true,
          message: "密码不能为空",
          trigger: ["blur", "change"],
        },
        { min: 6, max: 20, message: "密码长度6-20位", trigger: "blur" },
        {
          pattern: /^(?=.*[A-Za-z])(?=.*\d).+$/,
          message: "密码需包含字母和数字",
          trigger: "blur",
        },
      ],
      confirmPassword: [
        {
          required: true,
          message: "请再次输入密码",
          trigger: ["blur", "change"],
        },
        {
          validator: (rule, value, callback) => {
            if (value !== this.currentModel.password) {
              callback("两次输入的密码不一致");
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"],
        },
      ],
      realname: [
        {
          required: true,
          message: "真实姓名不能为空",
          trigger: ["blur", "change"],
        },
        { min: 2, max: 20, message: "真实姓名长度2-20位", trigger: "blur" },
      ],
      num: [
        {
          required: true,
          message: "工号不能为空",
          trigger: ["blur", "change"],
        },
        {
          pattern: /^[A-Za-z0-9]+$/,
          message: "工号仅支持字母和数字",
          trigger: "blur",
        },
      ],
      email: [
        {
          required: true,
          message: "邮箱不能为空",
          trigger: ["blur", "change"],
        },
        {
          type: "email",
          message: "请输入正确的邮箱格式",
          trigger: ["blur", "change"],
        },
      ],
      phone: [
        {
          required: true,
          message: "电话不能为空",
          message: "电话不能为空",
          trigger: ["blur", "change"],
        },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "请输入正确的手机号码",
          trigger: ["blur", "change"],
        },
      ],
      schoolId: [
        { required: true, message: "请选择学校", trigger: ["blur", "change"] },
      ],
      title: [
        {
          required: true,
          message: "职位不能为空",
          trigger: ["blur", "change"],
        },
      ],
    };

    // 数据初始化（从数据库获取）使用Vue响应式特性
    this.schools = ref([]);

    // 绑定事件
    this.handleSubmit = this.handleSubmit.bind(this);
    this.back = this.back.bind(this);

    // 从数据库加载数据
    this.loadSchools();
  }

  // 从数据库获取学校数据
  async loadSchools() {
    try {
      console.log("开始加载学校数据...");
      const im = await J.callApiAsync(
        "OBEvolutionAI.SchoolControl.get_list",
        {}
      );
      console.log("学校数据响应:", im);
      if (im && im.data) {
        const schoolsData = im.data.map((item) => ({
          value: item.schoolId,
          text: item.name,
        }));
        console.log("处理后的学校数据:", schoolsData);
        this.schools.value = schoolsData;
      } else {
        console.warn("学校数据为空或格式不正确");
      }
    } catch (error) {
      console.error("获取学校数据失败:", error);
    }
  }

  // 返回上一页
  back() {
    uni.navigateBack();
  }

  // 提交注册
  async handleSubmit(formRef) {
    // 检查表单引用
    if (!formRef) {
      console.error("表单引用未传递");
      return;
    }

    try {
      // 1. 表单验证阶段
      console.log("开始表单验证...");
      await formRef.validate();
      console.log("表单验证通过");

      // 2. 显示加载状态
      uni.showLoading({ title: "注册中..." });

      // 3. 调用后端API
      console.log("开始调用后端注册API...");
      const im = await J.callApiAsync("OBEvolutionAI.AdminControl.register", {
        username: this.currentModel.username,
        password: this.currentModel.password,
        realname: this.currentModel.realname,
        num: this.currentModel.num,
        email: this.currentModel.email,
        phone: this.currentModel.phone,
        schoolId: parseInt(this.currentModel.schoolId),
        title: this.currentModel.title,
      });

      // 4. 隐藏加载状态
      uni.hideLoading();

      // 5. 处理API响应
      if (im.success) {
        uni.showToast({ title: "注册成功，请等待审核", icon: "success" });
        setTimeout(() => {
          uni.redirectTo({ url: "/pages/user/login" });
        }, 1500);
      } else {
        // 错误提示细化
        const errorMap = {
          user_exists: "用户名已被占用，请更换",
          admin_num_exists: "该工号已注册",
          invalid_email: "邮箱格式错误",
          invalid_phone: "手机号格式错误",
          password_too_short: "密码长度不能少于6位",
          missing_fields: "缺少必要注册信息",
        };
        const msg = errorMap[im.data?.error_type] || im.msg || "注册失败";
        uni.showToast({ title: msg, icon: "none", duration: 3000 });
      }
    } catch (error) {
      // 验证失败或网络错误
      uni.hideLoading();
      console.log("表单验证失败或网络错误:", error);

      // 检查是否是验证错误
      if (error.errMsg) {
        uni.showToast({ title: error.errMsg, icon: "none" });
      } else if (error.message) {
        uni.showToast({ title: error.message, icon: "none" });
      } else {
        console.error("注册异常:", error);
        uni.showToast({ title: "网络错误，请稍后重试", icon: "none" });
      }
    }
  }
}

const D = new AdminRegisterControl();
export default D;